//导入重置样式
require("../../assets/css/reset.css");
//导入公共样式
require("../../assets/css/basic.css");
//导入标准样式
require("../../assets/css/normalize.css");
//导入iconfont.css
require("../../assets/fonts/iconfont.css");
//导入样式
require("./register.less");

//引入模块
const CaptchaMini = require("captcha-mini");
//引入js模块
const dom = require("../../utils/dom.js");
//引入axios
const axios = require("axios");

document.addEventListener("DOMContentLoaded", function () {
	//创建验证码
	let captcha = new CaptchaMini();
	let codeInit = "";
	captcha.draw(dom.get("#captcha"), (r) => {
		codeInit = r.toLowerCase();
	});
	//表单验证
	dom.get("#btn").addEventListener("click", function () {
		let error = dom.get("#error");
		//手机号验证
		let tel = dom.get("#tel").value;
		let reg = /^1[3456789]\d{9}$/i;
		if (reg.test(tel)) {
			error.textContent = "";
		} else {
			error.textContent = "手机号格式有误";
			return; //遇到错误时,停下来
		}
		//验证码验证
		let code = dom.get("#code").value;
		if (code === codeInit) {
			error.textContent = "";
		} else {
			error.textContent = "验证码错误";
			return; //遇到错误时,停下来
		}
		//密码验证
		let pwd = dom.get("#pwd").value;
		if (pwd.length >= 6) {
			error.textContent = "";
		} else {
			error.textContent = "密码必须写6位数以上";
			return; //遇到错误时,停下来
		}
		//确认密码验证
		let pwd2 = dom.get("#pwd2").value;
		if (pwd === pwd2) {
			error.textContent = "";
		} else {
			error.textContent = "两次输入密码不一致";
			return;
		}
		//通过验证，发送请求
		axios
			.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
				account: tel,
				password: pwd,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					location.href = "login.html";
					alert("恭喜你，注册成功！");
				} else {
					alert("注册失败，" + res.data.message);
				}
			});
	});
});
